import 'package:flutter/material.dart';

class LDXStarRating extends StatefulWidget {
  final double rating; //分数
  final double maxRating; //最大分数
  final int count; //显示个数
  final double size; //显示大小
  final Color unslectedCorlor; //未选中颜色
  final Color slectedColor; //选中颜色
  //自定义图片
  final Widget unslectedImage; //未选择时图片
  final Widget slectedImage; //选中时的图片

  LDXStarRating({
    required this.rating,
    this.maxRating = 10,
    this.count = 5,
    this.size = 30,
    this.unslectedCorlor = Colors.grey,
    this.slectedColor = Colors.red,
    unslectedImage,
    slectedImage,
  })  : unslectedImage = unslectedImage ?? Icon(Icons.star, color: unslectedCorlor, size: size),
        slectedImage = slectedImage ?? Icon(Icons.star, color: slectedColor, size: size);

  @override
  State<LDXStarRating> createState() => LDXStarRatingState();
}

class LDXStarRatingState extends State<LDXStarRating> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Row(mainAxisSize: MainAxisSize.min, children: buildUnselectStar()),
        Row(mainAxisSize: MainAxisSize.min, children: buildselectStar()),
      ],
    );
  }

  List<Widget> buildUnselectStar() {
    return List.generate(widget.count, (index) {
      return widget.unslectedImage;
    });
  }

  List<Widget> buildselectStar() {
    List<Widget> stars = [];
    final star = widget.slectedImage;
    //构建满填充的star
    double oneValue = widget.maxRating / widget.count;
    int entireCount = (widget.rating / oneValue).floor();
    for (var i = 0; i < entireCount; i++) {
      stars.add(star);
    }
    //构建部分starter
    double leftWidth = ((widget.rating / oneValue) - entireCount) * widget.size;
    final halfStar = ClipRect(
      clipper: LDXStarClipper(leftWidth),
      child: star,
    );
    stars.add(halfStar);
//满分裁剪
    if (stars.length > widget.rating) {
      return stars.sublist(0, widget.count);
    }
    return stars;
  }
}

class LDXStarClipper extends CustomClipper<Rect> {
  double width;

  LDXStarClipper(this.width);

  @override
  Rect getClip(Size size) {
    return Rect.fromLTRB(0, 0, width, size.height);
  }

  @override
  bool shouldReclip(LDXStarClipper oldClipper) {
    return oldClipper.width != this.width;
  }
}
